const express = require('express');
const path = require("path");

const { createProxyMiddleware } = require('http-proxy-middleware');

const axios = require("axios");

const app = express();

app.use(express.static(path.join(__dirname, 'public')));   // 静态资源服务

//  post表单的解析
app.use(express.urlencoded({ extended: false }));   // post表单  body

app.use(express.json());     // 以json方式发送的请求的  

// CORS：全称为 Cross-origin resource sharing，即跨域资源共享，它允许浏览器向跨域服务器发送 Ajax 请求，克服了 Ajax 只能同源使用的限制。

// cors  express中原始写法
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
    res.header('Access-Control-Allow-Methods', 'GET, POST');
    next();
})

// proxy 代理
/*
app.use('/wy', createProxyMiddleware({
    target: 'https://m.you.163.com/xhr/index.json',
    //将要代理的地址  127.0.0.1:3002/  ===>  https://m.you.163.com/xhr/index.json
    changeOrigin: true,	//  如果使用代理服务器，changeOrigin 的值只能为true
    pathRewrite: { // 路径重写（路径替换）
        "^/wy": "",   //被替换的路径: 新路径
    }
}));
*/

// http://127.0.0.1:3002/wy
// https://m.you.163.com/xhr/index.json/wy
// https://m.you.163.com/xhr/index.json


// 设置路由
const router = express.Router()


// 代理服务器的路由
router.get("/wyjson", (req, res) => {
    var params = req.query;
    axios({
        method: "get",
        url: "https://m.you.163.com/xhr/index.json",
        params: params
    }).then(response => {
        // console.log(response);  // 后台返回的数据
        res.json(response.data);
    }).catch(err => {
        res.json({
            msg: "请求出现异常"
        });
    });
});



app.use('/', router);  //  

app.listen(3002, () => {
    console.log('listen 3002');
})